"""
规则检查模块
负责执行违规检测规则和关键词匹配
"""

import re
import logging

logger = logging.getLogger(__name__)

class RuleChecker:
    """规则检查器"""

    def __init__(self, rules: dict):
        self.rules = rules

    def extract_text_from_quotes(self, text: str) -> list:
        """
        从引号中提取文字内容
        支持单引号、双引号和各种引号格式
        """
        import re
        extracted_texts = []

        # 匹配各种引号格式
        quote_patterns = [
            r'"([^"]*)"',      # 英文双引号
            r"'([^']*)'",      # 英文单引号
            r'"([^"]*)"',      # 中文双引号
            r'"([^"]*)"',      # 中文单引号
            r'`([^`]*)`',      # 反引号
        ]

        for pattern in quote_patterns:
            matches = re.findall(pattern, text)
            extracted_texts.extend(matches)

        return extracted_texts

    async def check_rules(self, image_analysis: str, ocr_text: str = "") -> dict:
        """
        检查规则违规情况
        增强版：同时检查AI分析结果、OCR识别文字和AI描述中的引号内容
        """
        details = []
        violated_rules = []
        detection_sources = {}  # 记录检测源信息

        # 1. 原始合并文本
        combined_text = f"{image_analysis} {ocr_text}".strip()

        # 2. 从AI分析结果中提取引号中的文字
        quoted_texts = self.extract_text_from_quotes(image_analysis)
        enhanced_text = combined_text

        # 将引号中的文字也加入到检查文本中
        if quoted_texts:
            quoted_combined = " ".join(quoted_texts)
            enhanced_text = f"{combined_text} {quoted_combined}".strip()

        logger.info(f"[规则检查] 增强文本长度: {len(enhanced_text)}")
        if quoted_texts:
            logger.info(f"[规则检查] 提取的引号文字: {quoted_texts}")

        for rule_name, rule_info in self.rules.items():
            matched = False
            matched_keywords = []
            detection_info = {
                "ocr_text": False,
                "ai_description": False,
                "quoted_content": False
            }

            for keyword in rule_info['keywords']:
                # 检查原始OCR文字
                if keyword in ocr_text:
                    if keyword not in matched_keywords:
                        matched = True
                        matched_keywords.append(keyword)
                        detection_info["ocr_text"] = True
                        logger.info(f"[规则检查] 在OCR文字中匹配关键词: '{keyword}'")

                # 检查AI分析结果
                if keyword in image_analysis:
                    if keyword not in matched_keywords:
                        matched = True
                        matched_keywords.append(keyword)
                        detection_info["ai_description"] = True
                        logger.info(f"[规则检查] 在AI描述中匹配关键词: '{keyword}'")

                # 检查引号中的文字（包含子串匹配）
                if quoted_texts and any(keyword in quoted or any(keyword in word for word in quoted.split()) for quoted in quoted_texts):
                    if keyword not in matched_keywords:
                        matched = True
                        matched_keywords.append(keyword)
                        detection_info["quoted_content"] = True
                        logger.info(f"[规则检查] 在引号内容中匹配关键词: '{keyword}'")

            if matched:
                violated_rules.append(rule_name)
                detection_sources[rule_name] = detection_info
                logger.info(f"[规则检查] 规则 '{rule_name}' 触发违规，匹配关键词: {matched_keywords}")

            details.append({
                "matched_conditions": matched_keywords,
                "rule_name": rule_name,
                "violated": matched,
                "detection_sources": detection_info
            })

        logger.info(f"[规则检查] 违规规则数量: {len(violated_rules)}")
        if violated_rules:
            logger.info(f"[规则检查] 违规规则: {', '.join(violated_rules)}")

        return {
            "details": details,
            "violated_rules": violated_rules,
            "detection_sources": detection_sources,
            "ocr_text": ocr_text,
            "quoted_texts": quoted_texts
        }
